package uy.com.tsi2G7.superbet.ui;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

import org.apache.commons.lang.StringUtils;

import uy.com.tsi2G7.superbet.account.AccountService;
import uy.com.tsi2G7.superbet.bet.BetService;
import uy.com.tsi2G7.superbet.bet.CompositeBet;
import uy.com.tsi2G7.superbet.bet.SimpleBet;
import uy.com.tsi2G7.superbet.event.EventMarket;
import uy.com.tsi2G7.superbet.event.EventMarketResult;
import uy.com.tsi2G7.superbet.event.EventService;
import uy.com.tsi2G7.superbet.util.Utils;

@ManagedBean(name = "userAccountBean")
@SessionScoped
public class UserAccountBean {
	@ManagedProperty(value="#{userBean}")
	private UserBean userBean;
	@EJB
	private BetService betService;
	@EJB
	private EventService eventService;
	@EJB
	private AccountService accountService; 
	private CompositeBet compositeBet=new CompositeBet();
	private List<BetHistoryDescriptor> compositeBetdescriptors=new ArrayList<BetHistoryDescriptor>();
	
	public CompositeBet getCompositeBet() {
		return compositeBet;
	}

	public List<BetHistoryDescriptor> getLastUserBets(){
		return betService.getlastUserSimpleBetsDescription(userBean.getMail());
	}
	
	public List<BetHistoryDescriptor> getPendingUserBets(){
		return betService.getPendingUserBetsDescription(userBean.getMail());
	}
	
	public boolean isCompositeBetEnabled(){
		return compositeBet.getBets()!=null&&compositeBet.getBets().length>0;
	}
	
	public String setWinner(){
		String market = PanelMenuBean.getViewParameter(PanelMenuBean.MARKET_VIEW_PARAMETER);
		String result = PanelMenuBean.getViewParameter(PanelMenuBean.MARKET_RESULT_VIEW_PARAMETER);
		try {
			betService.updateResultAndBets(Long.valueOf(market),Long.valueOf(result));
		} catch (Exception e) {
			this.showErrorMessage(e.getMessage());
		}
		return "welcome";
		
	}
	
	 public List<MarketDateEntry> getMarketsWithPendingResults(){
		 SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
	     Map<EventMarket, List<EventMarketResult>> markets = eventService.getMarketsWithPendingResults();
	    	 Map<String,List<MarketsDescriptor>> res=new HashMap<String, List<MarketsDescriptor>>();
			for (EventMarket market : markets.keySet()) {
				MarketsDescriptor mDesc = new MarketsDescriptor();
				mDesc.setId(market.getMarketId());
				mDesc.setName(market.getName());
				mDesc.setSource(market.getSource());
				mDesc.setStartDate(new SimpleDateFormat("dd/MM/yyyy HH:mm").format(market.getStartDate()));
				for (EventMarketResult result : markets.get(market)) {
					MarketsResultDescriptor markRes=new MarketsResultDescriptor();
					markRes.setAmount(new DecimalFormat("$ ###.##").format(result.getAmount().doubleValue()));
					markRes.setId(result.getId());
					markRes.setName(result.getName());
					markRes.setSource(result.getSource());
					mDesc.getChildren().add(markRes);
				}
				if(!res.containsKey(sdf.format(market.getStartDate())))
					res.put(sdf.format(market.getStartDate()), new ArrayList<MarketsDescriptor>());
				res.get(sdf.format(market.getStartDate())).add(mDesc);
			}
			ArrayList<MarketDateEntry> marketEntries = new ArrayList<MarketDateEntry>();
			for (String date : res.keySet()) {
				marketEntries.add(new MarketDateEntry(res.get(date),date));
			}
			return marketEntries;
		}
	

	public String activateAccount() {
		String outcome = null;
		try {
			Map<String, String> requestMap = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
			String mail = (String) requestMap.get("param1");
			System.out.println(mail);
			String accountId = StringUtils.split(Utils.desencriptar(mail),",,")[0];
			String pass = StringUtils.split(Utils.desencriptar(mail),",,")[1];
			//Activamos cuenta
		    accountService.activateAccount(accountId);
		    //Login usuario
		    userBean.login(accountId,pass);
		    outcome = "welcome";
		} catch (Exception ex) {
			this.showErrorMessage(ex.getMessage());
		}
		return outcome;
	}
	
	public void showInformationMessage(String message) {
		if (message == null || "".equals(message.trim())) {
			message = "Error desconocido. Contacte al administrador";
		}
		FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, message, null));
	}

	public void showWarningMessage(String message) {
		if (message == null || "".equals(message.trim())) {
			message = "Error desconocido. Contacte al administrador";
		}
		FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, message, null));
	}

	public void showErrorMessage(String message) {
		if (message == null || "".equals(message.trim())) {
			message = "Error desconocido. Contacte al administrador";
		}
		FacesContext.getCurrentInstance()
				.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, message, null));
	}
	
	public String getUserBalance() {
		try {
			return new DecimalFormat("$ ###.##").format(accountService.getAccount(userBean.getMail()).getBalance().doubleValue());
		} catch (Exception e) {
			return "$ 0";
		}
	}
	
	
	public UserBean getUserBean() {
		return userBean;
	}

	public void setUserBean(UserBean userBean) {
		this.userBean = userBean;
	}

	public BetService getBetService() {
		return betService;
	}

	public void setBetService(BetService betService) {
		this.betService = betService;
	}
	public void addBetToComposite(String mail, Long eventType, Long event, Long market,
			Long marketResult,String eventTypeName,String eventName, String marketName,String marketResultName) {
		List<SimpleBet> bets=new ArrayList<SimpleBet>();
		if(compositeBet.getBets()!=null&&compositeBet.getBets().length>0)
			for (SimpleBet simpleBet : compositeBet.getBets()) {
				bets.add(simpleBet);
			}
		compositeBet.setBets(new SimpleBet[bets.size()+1]);
		bets.add(new SimpleBet(mail,eventType,event,market,marketResult));
		bets.toArray(compositeBet.getBets());
		compositeBetdescriptors.add(new BetHistoryDescriptor(eventName, eventTypeName, marketName, marketResultName, null,null,null));
	}

	public List<BetHistoryDescriptor> getCompositeBetdescriptors() {
		return compositeBetdescriptors;
	}

	public void cleanCompsoiteBet() {
		compositeBet=new CompositeBet();
		compositeBetdescriptors=new ArrayList<BetHistoryDescriptor>();
		
	}	
	
}
